package cn.jari.erp.inventory

import com.csicit.ace.jpaleaf.repository.EnhancedJpaRepository
import com.csicit.ace.utils.ConditionalOnCloudApp
import liquibase.integration.spring.SpringLiquibase
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.autoconfigure.domain.EntityScan
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.core.io.DefaultResourceLoader
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
import org.springframework.data.jpa.repository.support.AceJpaRepositoryFactoryBean
import org.springframework.orm.jpa.JpaTransactionManager
import org.springframework.orm.jpa.JpaVendorAdapter
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
import org.springframework.transaction.PlatformTransactionManager
import javax.persistence.EntityManagerFactory
import javax.sql.DataSource

/*
 * 警告：代码由鲲舟平台生成，请勿手动修改。
 * Warn: This class file is generated by JARI-ACE platform, please do not modify manually。
 */

private const val INVENTORY_SERVICE_PRIMARY_DATASOURCE = "inventory-service-primary-ds"
private const val INVENTORY_SERVICE_PRIMARY_EMF = "inventory-service-primary-emf"
private const val INVENTORY_SERVICE_PRIMARY_TM = "inventory-serviceprimary-tm"

/**
 * inventory-service的数据源配置
 *
 * @author JARI-ACE
 */
@Configuration
open class InventoryServiceDatasourceAutoConfiguration {
    @ConditionalOnCloudApp
    @EnableJpaRepositories(
        basePackages = [
            "com.csicit.ace.jpaleaf.repository"],
        repositoryFactoryBeanClass = AceJpaRepositoryFactoryBean::class,
        repositoryBaseClass = EnhancedJpaRepository::class,
        entityManagerFactoryRef = INVENTORY_SERVICE_PRIMARY_EMF,
        transactionManagerRef = INVENTORY_SERVICE_PRIMARY_TM
    )
    @Configuration
    open class InventoryServicePrimaryDataSourceConfiguration {

        @Bean
        @ConfigurationProperties("spring.datasource.inventory-service-primary-ds")
        open fun inventoryServicePrimaryDataSourceProperties(): DataSourceProperties {
            return DataSourceProperties()
        }

        @Primary
        @Bean(name = [INVENTORY_SERVICE_PRIMARY_DATASOURCE])
        open fun inventoryServicePrimaryDatasource(): DataSource {
            return inventoryServicePrimaryDataSourceProperties().initializeDataSourceBuilder().build()
        }

        @Primary
        @Bean(name = [INVENTORY_SERVICE_PRIMARY_EMF, "entityManagerFactory"])
        open fun inventoryServicePrimaryEntityManagerFactory(
            @Qualifier(INVENTORY_SERVICE_PRIMARY_DATASOURCE) dataSource: DataSource?,
            builder: EntityManagerFactoryBuilder,
            jpaVendorAdapter: JpaVendorAdapter
        ): LocalContainerEntityManagerFactoryBean {
            val jpaProperties: MutableMap<String, Any?> = HashMap()
            jpaProperties["hibernate.physical_naming_strategy"] =
                "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy"
            jpaProperties["hibernate.implicit_naming_strategy"] =
                "org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy"
            for (entry in jpaVendorAdapter.jpaPropertyMap.entries) {
                jpaProperties[entry.key] = entry.value
            }
            return builder
                .dataSource(dataSource)
                .packages("cn.jari.erp.inventory.entities.primary")
                .properties(jpaProperties)
                .persistenceUnit("default")
                .build()
        }

        @Primary
        @Bean(name = [INVENTORY_SERVICE_PRIMARY_TM, "platformTransactionManager"])
        open fun inventoryServicePrimaryTransactionManager(
            @Qualifier(INVENTORY_SERVICE_PRIMARY_EMF) entityManagerFactory: EntityManagerFactory
        ): PlatformTransactionManager {
            return JpaTransactionManager(entityManagerFactory)
        }

        @Bean
        open fun inventoryServicePrimaryLiquibase(
            @Qualifier(INVENTORY_SERVICE_PRIMARY_DATASOURCE) dataSource: DataSource?): SpringLiquibase {
            val liquibase = SpringLiquibase()
            // 用户模块Liquibase文件路径
            liquibase.changeLog = "classpath:db/changelog/inventory-service/primary/change-log-master.xml";
            liquibase.dataSource = dataSource
            liquibase.setShouldRun(true)
            liquibase.resourceLoader = DefaultResourceLoader()
            return liquibase
        }
    }
}